package com.hongguan.oms.service.grid;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.hongguan.oms.common.Const;
import com.hongguan.oms.common.ConstGrid;
import com.hongguan.oms.domain.UserInfo;
import com.hongguan.oms.domain.gis.GisInfo;
import com.hongguan.oms.domain.grid.GridAddressInfo;
import com.hongguan.oms.domain.grid.GridAttachmentInfo;
import com.hongguan.oms.domain.grid.GridBaseStation;
import com.hongguan.oms.domain.grid.GridBaseStationExample;
import com.hongguan.oms.domain.grid.GridBsRepeater;
import com.hongguan.oms.domain.grid.GridBsRepeaterExample;
import com.hongguan.oms.domain.grid.GridBuildingInfo;
import com.hongguan.oms.domain.grid.GridContactInfo;
import com.hongguan.oms.domain.grid.GridFiberInfo;
import com.hongguan.oms.domain.grid.GridFiberInfoExample;
import com.hongguan.oms.domain.grid.GridGroupCustInfo;
import com.hongguan.oms.domain.grid.GridNetworkResource;
import com.hongguan.oms.domain.grid.GridOperatorsInfo;
import com.hongguan.oms.domain.grid.GridUnit;
import com.hongguan.oms.service.gis.GisService;
import com.hongguan.oms.utils.Util;

/**
 * GridAddressInfo Service
 * 
 * @author
 * 
 */
@Service
public class GridInfoSaveService {

	@Autowired
	private GridBuildingInfoService gridbuildinginfoService;

	@Autowired
	private GridAddressInfoService gridAddressInfoService;

	@Autowired
	private GridContactInfoService gridContactInfoService;

	@Autowired
	private GridOperatorsInfoService gridOperatorsInfoService;

	@Autowired
	private GridGroupCustInfoService gridGroupCustInfoService;

	@Autowired
	private GridAttachmentInfoService gridAttachmentInfoService;

	@Autowired
	private GisService gisService;

	@Autowired
	private GridNetworkResourceService gridNetworkResourceService;

	@Autowired
	private GridBaseStationService gridBaseStationService;

	@Autowired
	private GridBsRepeaterService gridBsRepeaterService;

	@Autowired
	private GridFiberInfoService gridFiberInfoService;
	
	@Autowired
	private GridUnitService gridUnitService;

	/**
	 * ����¥����Ϣ
	 * 
	 * @param request
	 */
	@Transactional
	public void saveBuildingInfo(HttpServletRequest request) throws Exception {
		GridBuildingInfo gridbuildinginfo = new GridBuildingInfo();
		Util.setDomainObjectPropertyFromRequest(request, gridbuildinginfo);
		GridUnit gridUnit = (GridUnit)gridbuildinginfo;
		gridUnit.setUnitName(gridbuildinginfo.getBuildingName());
		gridUnit.setUnitType(ConstGrid.UNIT_TYPE_BUILDING);
		Long unitId = gridUnit.getUnitId();
		if(unitId==null){
			/* ����Ӫ��Ԫ */
			unitId = gridUnitService.insert(gridUnit);
		}
		Long buildingId = gridbuildinginfo.getBuildingId();
		if (buildingId == null) {
			/* ����¥����Ϣ */
			buildingId = gridbuildinginfoService.insert(gridbuildinginfo);
		}
		/* ��ַ��Ϣ */
		GridAddressInfo addressInfo = new GridAddressInfo();// gridbuildinginfo.getAddressInfo();
		Util.setDomainObjectPropertyFromRequest(request, addressInfo,
				"addressInfo.");
		addressInfo.setAddressId(gridUnit.getAddressId());
		addressInfo.setEntityType(ConstGrid.ENTITY_TYPE_BUILDING);
		addressInfo.setEntityId(buildingId);
		gridAddressInfoService.saveGridAddressInfo(addressInfo);
		gridUnit.setAddressId(addressInfo.getAddressId());
		gridUnit.setAddressDetail(gridAddressInfoService.getAddressDetail(addressInfo));
		
		/* GIS ��Ϣ */
		String longitude = addressInfo.getLongitude();//����
		if(StringUtils.isBlank(longitude)||!StringUtils.isNumeric(longitude)){
			longitude = "0";
		}
		String latitude = addressInfo.getLatitude();//γ��
		if(StringUtils.isBlank(latitude)||!StringUtils.isNumeric(latitude)){
			latitude = "0";
		}
		String namepos = longitude + "," + latitude;
		String rectscale = "";
		if(request.getParameter("gisInfo.ecoordx")!=null && request.getParameter("gisInfo.ecoordx")!=null)
		{
			rectscale = rectscale + request.getParameter("gisInfo.ecoordx").toString()+","+request.getParameter("gisInfo.ecoordy").toString();
		}
		GisInfo gis = new GisInfo();
		Util.setDomainObjectPropertyFromRequest(request, gis, "gisInfo.");
		gis.setId(gridUnit.getGisId());
		if(gis.getIconId() == null){
			gis.setIconId(505);
		}
//		gis.setIsMain(1);
		gis.setNamePos(namepos);
		gis.setRectScale(rectscale);
		gis.setType(ConstGrid.GIS_TYPE_POINT);
		gisService.saveOrUpdateGis(gis);
		gridUnit.setGisId(gis.getId());

		/* ��Ӫ����Ϣ */
		GridOperatorsInfo operatorsInfo = new GridOperatorsInfo();// gridbuildinginfo.getOperatorsInfo();
		Util.setDomainObjectPropertyFromRequest(request, operatorsInfo,
				"operatorsInfo.");
		operatorsInfo.setGridId(buildingId);
		operatorsInfo.setOpsId(gridbuildinginfo.getOperators());
		gridOperatorsInfoService.saveGridOperatorsInfo(operatorsInfo);
		gridbuildinginfo.setOperators(operatorsInfo.getOpsId());

		/* ��ҵ��˾��Ϣ */
		GridGroupCustInfo propertyCompanyInfo = new GridGroupCustInfo();// gridbuildinginfo.getPropertyCompanyInfo();
		Util.setDomainObjectPropertyFromRequest(request, propertyCompanyInfo,
				"propertyCompanyInfo.");
		propertyCompanyInfo.setGridId(buildingId);
		propertyCompanyInfo.setCustType(ConstGrid.CUST_TYPE_PROP_COMP);
		propertyCompanyInfo.setCustId(gridbuildinginfo.getPropertyCompany());
		gridGroupCustInfoService.saveGridGroupCustInfo(propertyCompanyInfo);
		gridbuildinginfo.setPropertyCompany(propertyCompanyInfo.getCustId());

		/* ��������Ϣ */
		GridGroupCustInfo baInfo = new GridGroupCustInfo();// gridbuildinginfo.getBusinessAgentInfo();
		Util.setDomainObjectPropertyFromRequest(request, baInfo,
				"businessAgentInfo.");
		baInfo.setGridId(buildingId);
		baInfo.setCustType(ConstGrid.CUST_TYPE_BUSI_AGENT);
		baInfo.setCustId(gridbuildinginfo.getBusinessAgent());
		gridGroupCustInfoService.saveGridGroupCustInfo(baInfo);
		gridbuildinginfo.setBusinessAgent(baInfo.getCustId());

		/* jϵ����Ϣ */
		GridContactInfo pbContactInfo = new GridContactInfo();// gridbuildinginfo.getPbContactInfo();
		Util.setDomainObjectPropertyFromRequest(request, pbContactInfo,
				"pbContactInfo.");
		pbContactInfo.setEntityType(ConstGrid.ENTITY_TYPE_BUILDING);
		pbContactInfo.setContactType(ConstGrid.CONTACT_TYPE_PROP_BUSI);
		pbContactInfo.setEntityId(buildingId);
		gridContactInfoService.saveGridContactInfo(pbContactInfo);

		GridContactInfo pmContactInfo = new GridContactInfo();// gridbuildinginfo.getPmContactInfo();
		Util.setDomainObjectPropertyFromRequest(request, pmContactInfo,
				"pmContactInfo.");
		pmContactInfo.setEntityType(ConstGrid.ENTITY_TYPE_BUILDING);
		pmContactInfo.setContactType(ConstGrid.CONTACT_TYPE_PROP_MGR);
		pmContactInfo.setEntityId(buildingId);
		gridContactInfoService.saveGridContactInfo(pmContactInfo);

		GridContactInfo ppContactInfo = new GridContactInfo();
		Util.setDomainObjectPropertyFromRequest(request, ppContactInfo,
				"ppContactInfo.");
		ppContactInfo.setEntityType(ConstGrid.ENTITY_TYPE_BUILDING);
		ppContactInfo.setContactType(ConstGrid.CONTACT_TYPE_PROP_PROJ);
		ppContactInfo.setEntityId(buildingId);
		gridContactInfoService.saveGridContactInfo(ppContactInfo);

		GridContactInfo dcContactInfo = new GridContactInfo();
		Util.setDomainObjectPropertyFromRequest(request, dcContactInfo,
				"dcContactInfo.");
		dcContactInfo.setEntityType(ConstGrid.ENTITY_TYPE_BUILDING);
		dcContactInfo.setContactType(ConstGrid.CONTACT_TYPE_DEVELOP_COMP);
		dcContactInfo.setEntityId(buildingId);
		gridContactInfoService.saveGridContactInfo(dcContactInfo);

		GridContactInfo baContactInfo = new GridContactInfo();
		Util.setDomainObjectPropertyFromRequest(request, baContactInfo,
				"baContactInfo.");
		baContactInfo.setEntityType(ConstGrid.ENTITY_TYPE_BUILDING);
		baContactInfo.setContactType(ConstGrid.CONTACT_TYPE_BUSI_AGENT);
		baContactInfo.setEntityId(buildingId);
		gridContactInfoService.saveGridContactInfo(baContactInfo);

		/* ¥��ͼƬ */
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> fileList = multipartRequest
				.getFiles("buildingPics");
		String filePath = request.getSession().getServletContext().getRealPath(
				"/")
				+ "upload/building/";
		for (MultipartFile mfile : fileList) {
			String attaName = ((CommonsMultipartFile) mfile)
					.getOriginalFilename();
			if (StringUtils.isNotBlank(attaName) && mfile.getSize() > 0) {
				String fileName = System.currentTimeMillis() + "_" + attaName;
				mfile.transferTo(new File(filePath + fileName));
				GridAttachmentInfo gridattachmentinfo = new GridAttachmentInfo();
				gridattachmentinfo
						.setEntityType(ConstGrid.ENTITY_TYPE_BUILDING);
				gridattachmentinfo
						.setAttaType(ConstGrid.ATTA_TYPE_BUILDING_PIC);
				gridattachmentinfo.setEntityId(buildingId);
				gridattachmentinfo.setAttaName(attaName);
				gridattachmentinfo.setFileName(fileName);
				gridattachmentinfo.setFilePath(filePath);
				gridAttachmentInfoService
						.saveGridAttachmentInfo(gridattachmentinfo);
			}
		}

		/* ����¥����Ϣ */
		gridbuildinginfoService.saveGridBuildingInfo(gridbuildinginfo);
		/* ����Ӫ��Ԫ��Ϣ */
		gridUnitService.saveGridUnit(gridUnit);
	}

	/**
	 * ɾ��¥����Ϣ
	 * 
	 * @param request
	 */
	@Transactional
	public void deleteBuildingInfo(HttpServletRequest request) throws Exception {
		Long buildingId = Util.getLong(request, "buildingId");
		GridBuildingInfo gridbuildinginfo = new GridBuildingInfo();
		gridbuildinginfo.setBuildingId(buildingId);
		gridbuildinginfo = gridbuildinginfoService
				.selectByPrimaryKey(gridbuildinginfo);

		/* ɾ��GIS��Ϣ */
		Long gisId = gridbuildinginfo.getGisId();
		if (gisId != null) {
			gisService.deleteGisInfoById(gisId);
		}

		/* ɾ���ַ��Ϣ */
		Long addressId = gridbuildinginfo.getAddressId();
		if (addressId != null) {
			GridAddressInfo addressInfo = new GridAddressInfo();
			addressInfo.setAddressId(addressId);
			gridAddressInfoService.deleteGridAddressInfo(addressInfo);
		}

		/* ɾ����Ӫ����Ϣ */
		Long opsId = gridbuildinginfo.getOperators();
		if (opsId != null) {
			GridOperatorsInfo operatorsInfo = new GridOperatorsInfo();
			operatorsInfo.setOpsId(opsId);
			gridOperatorsInfoService.deleteGridOperatorsInfo(operatorsInfo);
		}

		/* ɾ����ҵ��˾��Ϣ */
		Long propId = gridbuildinginfo.getPropertyCompany();
		if (propId != null) {
			GridGroupCustInfo propertyInfo = new GridGroupCustInfo();
			propertyInfo.setCustId(propId);
			gridGroupCustInfoService.deleteGridGroupCustInfo(propertyInfo);
		}

		/* ɾ���������Ϣ */
		Long baId = gridbuildinginfo.getBusinessAgent();
		if (baId != null) {
			GridGroupCustInfo baInfo = new GridGroupCustInfo();
			baInfo.setCustId(baId);
			gridGroupCustInfoService.deleteGridGroupCustInfo(baInfo);
		}

		/* ɾ��¥����Ϣ */
		gridbuildinginfoService.deleteGridBuildingInfo(gridbuildinginfo);
		/* ɾ��Ӫ��Ԫ */
		gridUnitService.deleteGridUnit(gridbuildinginfo);

	}

	/**
	 * ����������Դ
	 * 
	 * @param request
	 */
	@Transactional
	public void saveNetworkResource(HttpServletRequest request)
			throws Exception {
		GridNetworkResource gridNetworkResource = new GridNetworkResource();
		Util.setDomainObjectPropertyFromRequest(request, gridNetworkResource);
		Long nrId = gridNetworkResource.getNrId();
		Integer nrType = gridNetworkResource.getNrType();

		/* ��ַ��Ϣ */
		GridAddressInfo addressInfo = new GridAddressInfo();
		Util.setDomainObjectPropertyFromRequest(request, addressInfo,
				"addressInfo.");
		addressInfo.setEntityType(ConstGrid.ENTITY_TYPE_NETWORK_RESOURCE);
		addressInfo.setEntityId(nrId);
		addressInfo.setAddressId(gridNetworkResource.getNrAddress());
		gridAddressInfoService.saveGridAddressInfo(addressInfo);

		/* GIS ��Ϣ */
		String namepos ="";
		GisInfo gisInfo = new GisInfo();
		Util.setDomainObjectPropertyFromRequest(request, gisInfo, "gisInfo.");
		gisInfo.setIsMain(1);
		
		//������˵��������
		if(ConstGrid.NETWORK_RESOURCE_TYPE_FIBER == nrType){
			String[] str = gisInfo.getCoordsInfo().toString().split(",");
			int xMax = 0, yMax = 0, xMin = Integer.MAX_VALUE, yMin = Integer.MAX_VALUE;
			boolean flg = true;
			for(int i=0;i<str.length;i++){
				if(flg){
					if(xMax<Integer.parseInt(str[i].toString())){
						xMax = Integer.parseInt(str[i].toString());
					}
					if(xMin>Integer.parseInt(str[i].toString())){
						xMin = Integer.parseInt(str[i].toString());
					}
					flg=false;
				}else{
					if(yMax<Integer.parseInt(str[i].toString())){
						yMax = Integer.parseInt(str[i].toString());
					}
					if(yMin>Integer.parseInt(str[i].toString())){
						yMin = Integer.parseInt(str[i].toString());
					}
					flg=true;
				}
			}		
			 namepos = ((xMax + xMin) / 2) + "," + ((yMax + yMin) / 2);
		}else{
			 namepos = addressInfo.getLongitude() + ","+ addressInfo.getLatitude();//��վ��ֱ��վ
		}
		
		gisInfo.setNamePos(namepos);
		gisService.saveOrUpdateGis(gisInfo);

		/* ������Դ */
		gridNetworkResource.setNrAddress(addressInfo.getAddressId());
		gridNetworkResource.setGisId(gisInfo.getId());
		gridNetworkResource.setNrAddressDetail(gridAddressInfoService
				.getAddressDetail(addressInfo));
		gridNetworkResourceService.saveGridNetworkResource(gridNetworkResource);
		nrId = gridNetworkResource.getNrId();

		if (ConstGrid.NETWORK_RESOURCE_TYPE_BS == nrType) {
			/* ��վ��Ϣ */
			GridBaseStation gridBaseStation = new GridBaseStation();
			Util.setDomainObjectPropertyFromRequest(request, gridBaseStation);
			gridBaseStation.setNrId(nrId);
			Long bsId = gridBaseStation.getBsId();
			if (bsId == null) {
				/* ������վ */
				gridBaseStationService.insert(gridBaseStation);
			}

			/* jϵ����Ϣ */
			/* ��緿jϵ�� */
			GridContactInfo erContactInfo = new GridContactInfo();
			Util.setDomainObjectPropertyFromRequest(request, erContactInfo,
					"erContactInfo.");
			erContactInfo.setEntityType(ConstGrid.ENTITY_TYPE_BASE_STATION);
			erContactInfo
					.setContactType(ConstGrid.CONTACT_TYPE_ELECTRICAL_ROOM);
			erContactInfo.setEntityId(bsId);
			gridContactInfoService.saveGridContactInfo(erContactInfo);
			gridBaseStation.setElectricalRoomContract(erContactInfo
					.getContactId());

			/* ҵ��jϵ�ˣ����죩 */
			GridContactInfo dayContactInfo = new GridContactInfo();
			Util.setDomainObjectPropertyFromRequest(request, dayContactInfo,
					"dayContactInfo.");
			dayContactInfo.setEntityType(ConstGrid.ENTITY_TYPE_BASE_STATION);
			dayContactInfo.setContactType(ConstGrid.CONTACT_TYPE_OWNER_DAY);
			dayContactInfo.setEntityId(bsId);
			gridContactInfoService.saveGridContactInfo(dayContactInfo);
			gridBaseStation.setDayContract(dayContactInfo.getContactId());

			/* ҵ��jϵ�ˣ�ҹ�䣩 */
			GridContactInfo nightContactInfo = new GridContactInfo();
			Util.setDomainObjectPropertyFromRequest(request, nightContactInfo,
					"nightContactInfo.");
			nightContactInfo.setEntityType(ConstGrid.ENTITY_TYPE_BASE_STATION);
			nightContactInfo.setContactType(ConstGrid.CONTACT_TYPE_OWNER_NIGHT);
			nightContactInfo.setEntityId(bsId);
			gridContactInfoService.saveGridContactInfo(nightContactInfo);
			gridBaseStation.setNightContract(nightContactInfo.getContactId());

			/* ҵ��jϵ�ˣ��ڼ��գ� */
			GridContactInfo holidayContactInfo = new GridContactInfo();
			Util.setDomainObjectPropertyFromRequest(request,
					holidayContactInfo, "holidayContactInfo.");
			holidayContactInfo
					.setEntityType(ConstGrid.ENTITY_TYPE_BASE_STATION);
			holidayContactInfo
					.setContactType(ConstGrid.CONTACT_TYPE_OWNER_HOLIDAY);
			holidayContactInfo.setEntityId(bsId);
			gridContactInfoService.saveGridContactInfo(holidayContactInfo);
			gridBaseStation.setHolidayContract(holidayContactInfo
					.getContactId());

			/* ���ά�������� */
			GridContactInfo maintenanceContactInfo = new GridContactInfo();
			Util.setDomainObjectPropertyFromRequest(request,
					maintenanceContactInfo, "maintenanceContactInfo.");
			maintenanceContactInfo
					.setEntityType(ConstGrid.ENTITY_TYPE_BASE_STATION);
			maintenanceContactInfo
					.setContactType(ConstGrid.CONTACT_TYPE_MAINTENANCE);
			maintenanceContactInfo.setEntityId(bsId);
			gridContactInfoService.saveGridContactInfo(maintenanceContactInfo);
			gridBaseStation.setMaintenanceContract(maintenanceContactInfo
					.getContactId());

			/* ���»�վ */
			UserInfo user = (UserInfo)request.getSession().getAttribute(Const.SESSION_USER);
			if(user!=null){
				gridBaseStation.setUpdateUserId(user.getId());
			}
			gridBaseStation.setUpdateDate(new Date());
			gridBaseStationService.saveGridBaseStation(gridBaseStation);
		} else if (ConstGrid.NETWORK_RESOURCE_TYPE_RPT == nrType) {
			/* ֱ��վ��Ϣ */
			GridBsRepeater gridBsRepeater = new GridBsRepeater();
			Util.setDomainObjectPropertyFromRequest(request, gridBsRepeater);
			gridBsRepeater.setNrId(nrId);
			gridBsRepeaterService.saveGridBsRepeater(gridBsRepeater);

		} else if (ConstGrid.NETWORK_RESOURCE_TYPE_FIBER == nrType) {
			/* ������Ϣ */
			GridFiberInfo gridFiberInfo = new GridFiberInfo();
			Util.setDomainObjectPropertyFromRequest(request, gridFiberInfo);
			gridFiberInfo.setNrId(nrId);
			gridFiberInfoService.saveGridFiberInfo(gridFiberInfo);
		}
	}

	/**
	 * ɾ��������Դ
	 * 
	 * @param request
	 */
	@Transactional
	public void deleteNetworkResource(HttpServletRequest request) {
		Long nrId = Util.getLong(request, "nrId");
		GridNetworkResource gridNetworkResource = new GridNetworkResource();
		gridNetworkResource.setNrId(nrId);
		gridNetworkResource = gridNetworkResourceService
				.selectByPrimaryKey(gridNetworkResource);
		Integer nrType = gridNetworkResource.getNrType();

		/* ɾ��GIS��Ϣ */
		Long gisId = gridNetworkResource.getGisId();
		if (gisId != null) {
			gisService.deleteGisInfoById(gisId);
		}

		/* ɾ���ַ��Ϣ */
		Long addressId = gridNetworkResource.getNrAddress();
		if (addressId != null) {
			GridAddressInfo addressInfo = new GridAddressInfo();
			addressInfo.setAddressId(addressId);
			gridAddressInfoService.deleteGridAddressInfo(addressInfo);
		}
		
		if (ConstGrid.NETWORK_RESOURCE_TYPE_BS == nrType) {
			/* ɾ���վ��Ϣ */
			GridBaseStationExample example = new GridBaseStationExample();
			example.createCriteria().andNrIdEqualTo(nrId);
			gridBaseStationService.deleteByExample(example);

		} else if (ConstGrid.NETWORK_RESOURCE_TYPE_RPT == nrType) {
			/* ɾ��ֱ��վ��Ϣ */
			GridBsRepeaterExample example = new GridBsRepeaterExample();
			example.createCriteria().andNrIdEqualTo(nrId);
			gridBsRepeaterService.deleteByExample(example);

		} else if (ConstGrid.NETWORK_RESOURCE_TYPE_FIBER == nrType) {
			/* ɾ�������Ϣ */
			GridFiberInfoExample example = new GridFiberInfoExample();
			example.createCriteria().andNrIdEqualTo(nrId);
			gridFiberInfoService.deleteByExample(example);
		}

		/* ɾ��������Դ */
		gridNetworkResourceService
				.deleteGridNetworkResource(gridNetworkResource);

	}

}
